package com.bibrApp.difu.actvity.register_mvp;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bibrApp.difu.R;
import com.bibrApp.difu.actvity.account_verify_mvp.AccountVerifyActivity;
import com.bibrApp.difu.base.BaseActivity;
import com.bibrApp.difu.utils.CheckUtils;
import com.bibrApp.difu.utils.IntentUtil;
import com.bibrApp.difu.utils.ToastUtils;
import com.google.android.material.tabs.TabLayout;
import com.gyf.barlibrary.ImmersionBar;


import butterknife.BindView;
import butterknife.OnClick;

public class RegisterActivity extends BaseActivity<RegisterPresenter> implements IRegisterView, TextWatcher, TabLayout.OnTabSelectedListener {

    private ImmersionBar mImmersionBar;
    private Context mContext;


    @BindView(R.id.register_tab_layout)
    TabLayout tabLayout;
    private static final String[] tabs = {"手机注册", "邮箱注册"};
    @BindView(R.id.register_account_et)
    EditText accountET;

    @BindView(R.id.register_pwd_et)
    EditText pwdET;
    @BindView(R.id.register_pwd_eye_iv)
    ImageView pwdEyeIV;
    @BindView(R.id.register_pwd_hint_tv)
    TextView pwdHintTV;
    @BindView(R.id.register_account_hint_tv)
    TextView accountHintTV;

    @BindView(R.id.register_content_ll)
    ScrollView registerContentLL;

    @BindView(R.id.tv_register_protocol)
    TextView tvRegisterProtocol;

    private CountTimer timer;

    @Override
    protected void initPresenter() {
        presenter = new RegisterPresenter(this, this);
        presenter.init();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        mContext = this;
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)
                .init();


        tvRegisterProtocol.setText(Html.fromHtml(String.format("%s%s", "点击\"下一步\"即视为同意", "<font color='#56cec0'>《迪富服务协议》</font>")));

        tabLayout.addTab(tabLayout.newTab().setText(tabs[0]));
        tabLayout.addTab(tabLayout.newTab().setText(tabs[1]));
        tabLayout.getTabAt(0).select();
        tabLayout.addOnTabSelectedListener(this);
    }


    private String accountString;//账户
    private String pwdString;//密码

    private boolean checkRegisterInfo() {
        accountString = accountET.getText().toString();
        pwdString = pwdET.getText().toString();
        if (tabLayout.getSelectedTabPosition() == 0) {//手机
            if (!TextUtils.isEmpty(accountString) && CheckUtils.isMobile(accountString)) {
                accountHintTV.setVisibility(View.INVISIBLE);
                if (!TextUtils.isEmpty(pwdString) && pwdString.length() > 5 && pwdString.length() < 19) {
                    pwdHintTV.setVisibility(View.INVISIBLE);
                    return true;
                } else {
                    pwdHintTV.setVisibility(View.VISIBLE);
                    pwdHintTV.setText("请设置6-18位密码");
                }
            } else {
                accountHintTV.setVisibility(View.VISIBLE);
                accountHintTV.setText("手机格式错误");
            }

        } else {//邮箱
            if (!TextUtils.isEmpty(accountString) && CheckUtils.isEmail(accountString)) {
                accountHintTV.setVisibility(View.INVISIBLE);
                if (!TextUtils.isEmpty(pwdString) && pwdString.length() > 5 && pwdString.length() < 19) {
                    pwdHintTV.setVisibility(View.INVISIBLE);
                    return true;
                } else {
                    pwdHintTV.setVisibility(View.VISIBLE);
                    pwdHintTV.setText("请设置6-18位密码");
                }
            } else {
                accountHintTV.setVisibility(View.VISIBLE);
                accountHintTV.setText("邮箱格式错误");
            }
        }
        return false;
    }


    //验证手机失败
    @Override
    public void error(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        ToastUtils.ShowToast(mContext, msg);
    }

    @OnClick({R.id.register_return, R.id.register_login_tv})
    public void loginOnclick() {
        finish();
    }

    @OnClick(R.id.register_next)
    public void nextOnclick() {
        if(checkRegisterInfo()){
            Bundle bundle = new Bundle();
            bundle.putString("account",accountString);
            bundle.putString("pwd",pwdString);
            IntentUtil.toActivity(AccountVerifyActivity.class,this,bundle);
        }
    }


    @OnClick(R.id.register_pwd_eye_iv)
    public void eyeIVOnclick() {
        if (pwdET.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
            pwdET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            pwdEyeIV.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icon_close));
        } else {
            pwdET.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            pwdEyeIV.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icon_eye));
        }

    }


    /**
     * mobile	手机号/邮箱	是	String	手机号，邮箱地址任一
     * password	密码	是	String
     * mobileVcode	验证码	是	Int
     * parentId	邀请码	否	string
     */
    /*@OnClick(R.id.register_btn)
    public void registerOnclick() {
        if (!TextUtils.isEmpty(verifyCodeET.getText().toString())) {
            if (verifyCodeET.getText().toString().length() < 4) {
                verifyCodeHintTV.setText("请输入正确验证码");
            } else {
                RegisterBody registerBody = new RegisterBody();
                registerBody.setMobile(accountString);
                registerBody.setPassword(pwdAgainString);
                registerBody.setMobileVcode(Integer.parseInt(verifyCodeET.getText().toString().replaceAll(" ", "")));
                if (!TextUtils.isEmpty(recCodeET.getText().toString())) {
                    registerBody.setParentId(recCodeET.getText().toString());
                } else {
                    registerBody.setParentId(null);
                }
                Map<String, String> map = EncryptUtils.encrypt(registerBody);
                if (NetWorkUtil.isNetWorkConnected(mContext)) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (NetWorkUtil.isNetworkAvailable(mContext)) {
                            presenter.register(map);
                        } else {
                            ToastUtils.ShowToast(mContext, "网络连接不可用，请您检查网络");
                        }
                    } else {
                        presenter.register(map);
                    }

                } else {
                    ToastUtils.ShowToast(mContext, "网络连接不可用，请您检查网络");
                }
            }
        } else {
            verifyCodeHintTV.setText("验证码不能为空");
        }

    }*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
       /* String firstETStr = verifyCodeET.getText().toString().replaceAll(" ", "");
        if (!TextUtils.isEmpty(firstETStr) && firstETStr.length() >= 4) {
            registerBtn.setEnabled(true);
            registerBtn.setClickable(true);
        } else {
            registerBtn.setEnabled(false);
            registerBtn.setClickable(false);
        }*/
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        switch (tab.getPosition()) {
            case 0:
                tabLayout.getTabAt(0).select();
                changeView(0);
                break;
            case 1:
                tabLayout.getTabAt(1).select();
                changeView(1);
                break;
        }
    }

    private void changeView(int i) {
        if (i == 0) {//手机注册
            accountET.setHint(R.string.register_phone_hint);
        } else {
            accountET.setHint(R.string.register_email_hint);
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    class CountTimer extends CountDownTimer {

        public CountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
           /* getCodeTV.setEnabled(true);
            getCodeTV.setClickable(true);
            getCodeTV.setText("点击获取");
            getCodeTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    getCode();
                }
            });*/
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
//            getCodeTV.setText((millisUntilFinished / 1000) + "S" + "重新获取");
        }
    }
}
